precision mediump float;

attribute vec3 a_position;
attribute vec3 a_normal;

uniform mat4 projMatrix;
uniform mat4 mvMatrix;
uniform mat4 nvMatrix;  // viewMatrix * normalMatrix  ,用于变换法线
uniform mat4 viewMatrix;

uniform mat4 lightMVPMatrix;

// 光照
uniform vec3 u_ambientColor;

// 方向光
struct DirLight{
    vec3 dir;
    vec3 color;
    float shiness;
};

uniform DirLight u_dirLight;
uniform vec3 u_color; // 物体的颜色

varying vec3 v_color;
varying vec4 v_clipPos4;
void main() {

    vec4 posInView = mvMatrix * vec4(a_position, 1.0);

    // 在相机空间计算漫反射
    vec3 normalInView = normalize((nvMatrix * vec4(a_normal,0.0)).xyz);
    vec3 dirLightDirInView = normalize((viewMatrix * vec4(u_dirLight.dir,0.0)).xyz);

    // 计算漫反射
    float diffFactor = max(dot(normalInView,dirLightDirInView),0.0);
    vec3 diffuseColor = diffFactor * u_dirLight.color;

    // 计算镜面反射
    vec3 refDir = normalize(reflect(-dirLightDirInView,normalInView));
    vec3 posToEye = normalize(-posInView.xyz);
    float specFactor = dot(refDir,posToEye);

    vec3 specColor = vec3(0.0);
    if(specFactor > 0.0){
        specFactor = pow(specFactor,u_dirLight.shiness);
        specColor = specFactor * u_dirLight.color;
    }

    v_clipPos4 = lightMVPMatrix * vec4(a_position, 1.0);
    gl_Position = projMatrix * posInView;
    vec3 finalColor = (u_ambientColor + diffuseColor + specColor) * u_color;
    v_color = finalColor;
}
